import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.blueAccent,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('社交媒体页面'),
        ),
        body: SocialMediaPage(),
      ),
    );
  }
}

class SocialMediaPage extends StatefulWidget {
  @override
  _SocialMediaPageState createState() => _SocialMediaPageState();
}

class _SocialMediaPageState extends State<SocialMediaPage> {
  int likes = 0;
  bool isLiked = false;
  List<String> comments = [];
  TextEditingController _commentController = TextEditingController();

  @override
  void initState() {
    super.initState();
    // 初始化点赞数和评论列表
    likes = 0;
    comments = [];
  }

  // 更新点赞数
  void likePost() async {
    setState(() {
      if (isLiked) {
        likes--; // 减少点赞数
      } else {
        likes++; // 增加点赞数
      }
      isLiked = !isLiked; // 切换点赞状态
    });
  }

  // 添加评论
  void addComment(String comment) async {
    setState(() {
      comments.add(comment); // 本地立即更新评论列表
    });

    try {
      final response = await http.post(
        Uri.parse('https://jsonplaceholder.typicode.com/posts/1/comments'),
        body: json.encode({'comment': comment}),
        headers: {'Content-Type': 'application/json'},
      );
      if (response.statusCode != 201) {
        throw Exception('Failed to add comment');
      }
    } catch (e) {
      print('Error: $e');
      setState(() {
        comments.removeLast(); // 回滚评论
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Row(
          children: [
            Expanded(
              child: Container(
                padding: EdgeInsets.all(16.0),
                color: Colors.grey[200],
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    CircleAvatar(
                      radius: 30, // 头像半径大小
                      backgroundImage: AssetImage('assets/头像.jpg'), // 头像图片路径
                    ),
                    SizedBox(width: 16.0), // 调整头像和帖子内容的间距
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '用户名',
                            style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
                          ),
                          SizedBox(height: 8.0), // 增加用户名和内容的间距
                          Text(
                            '帖子内容',
                            style: TextStyle(fontSize: 16.0),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        Container(
          padding: EdgeInsets.all(16.0),
          color: Colors.white,
          child: Row(
            children: <Widget>[
              IconButton(
                icon: Icon(Icons.thumb_up, color: isLiked ? Colors.blueAccent : Colors.grey),
                onPressed: likePost,
              ),
              SizedBox(width: 8.0),
              Text(
                '点赞 $likes',
                style: TextStyle(color: isLiked ? Colors.blueAccent : Colors.grey),
              ),
              SizedBox(width: 16.0),
              Icon(Icons.chat_bubble_outline, color: Colors.blueAccent),
              SizedBox(width: 8.0),
              GestureDetector(
                onTap: () {
                  // 点击评论按钮时弹出对话框让用户输入评论
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        title: Text('添加评论'),
                        content: TextField(
                          controller: _commentController,
                          decoration: InputDecoration(hintText: '请输入评论'),
                        ),
                        actions: <Widget>[
                          TextButton(
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            child: Text('取消'),
                          ),
                          TextButton(
                            onPressed: () {
                              // 添加评论并关闭对话框
                              if (_commentController.text.isNotEmpty) {
                                addComment(_commentController.text);
                                _commentController.clear();
                              }
                              Navigator.of(context).pop();
                            },
                            child: Text('确定'),
                          ),
                        ],
                      );
                    },
                  );
                },
                child: Text(
                  '评论 ${comments.length}',
                  style: TextStyle(color: Colors.blueAccent),
                ),
              ),
            ],
          ),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: comments.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(
                  '评论 ${index + 1}: ${comments[index]}',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
              );
            },
          ),
        ),
      ],
    );
  }
}
